<template>
  <page-meta :page-style="'overflow:'+(showCalendars?'hidden':'visible')"></page-meta>

  <view class="container">
    <uv-notice-bar v-if="unreadMessage.length>0" :text="unreadMessage" mode="link" direction="column"
                   url="/pages/msg/msg" link-type="switchTab"></uv-notice-bar>

    <uv-swiper :list="listswiper" indicator indicatorMode="line" circular></uv-swiper>

    <qiun-title-bar title="待办事项"/>
    <uv-grid :border="false" @click="onClick">
      <uv-grid-item v-for="(item,index) in list" :key="index">
        <view class="card">
          <uv-text color="#ffffff" :text="item.title" size="16" align="center"></uv-text>
          <uv-text  customStyle="font-size: 16px;color: #ffffff;margin-bottom: 5px;display: flex; justify-content: center;align-items: center;width: 100%;" :text="item.count" size="16" align="center"></uv-text>
        </view>
      </uv-grid-item>
    </uv-grid>

    <!-- 管理员、店长、部门经理 角色 -->
    <view v-if="authority && !authority.includes('employee')">
      <view>
        <!-- 日历 -->
        <uv-calendars mode="range" ref="calendars" allowSameDay @confirm="confirmCalendars" rangePrompt="31"/>
      </view>

      <view style="display: flex;">
        <qiun-title-bar title="考勤统计(日)"/>
        <uv-text type="info" prefixIcon="calendar" :text="rangeData" @click="openCalendars" align="right"></uv-text>
      </view>
      <uv-grid :border="false" @click="onClickDeptCount">
        <uv-grid-item v-for="(item,index) in deptCountList" :key="index">
          <view class="card">
            <uv-text color="#ffffff" :text="item.title" size="16" align="center"></uv-text>
            <uv-count-to :startVal="0" :endVal="item.count"
                         customStyle="font-size: 16px;color: #ffffff;margin-bottom: 5px;display: flex; justify-content: center;align-items: center;width: 100%;"></uv-count-to>
          </view>
        </uv-grid-item>
      </uv-grid>
      <qiun-data-charts canvas2d type="column" :opts="activeOpts" :chartData="attendanceStatisticsData"/>

      <view style="display: flex;">
        <qiun-title-bar title="收支统计(日)"/>
        <uv-text type="info" prefixIcon="calendar" :text="rangeData" @click="openCalendars" align="right"></uv-text>
      </view>
      <view class="charts-box">
        <qiun-data-charts type="line" :opts="opts" :chartData="dayIncomeExpenditureStatisticsData" canvas2d
                          :echartsH5="true" :echartsApp="true"/>
      </view>

      <qiun-title-bar title="收支统计(月)"/>
      <view class="charts-box">
        <qiun-data-charts type="line" :opts="opts" :chartData="monthIncomeExpenditureStatisticsData" canvas2d
                          :echartsH5="true" :echartsApp="true"/>
      </view>

      <qiun-title-bar title="区域评分"/>
    </view>
    <view v-else>
      <!-- 员工角色 显示个人信息     -->
      <qiun-title-bar title="综合评分"/>
      <view class="rate">
        <uv-text type="info" text="当月评分:"></uv-text>
        <uv-rate size="20" v-model="rate" :allowHalf="true" readonly></uv-rate>
        <uv-text type="info" :text="rate"></uv-text>
      </view>
      <uv-text type="info" text="历史评分:"></uv-text>
    </view>

    <!-- 评分图表 -->
    <view class="charts-box">
      <qiun-data-charts type="line" :opts="opts" :chartData="scoreStatisticsData" :echartsH5="true"
                        :echartsApp="true"/>
    </view>

    <qiun-title-bar title="任务"/>
    <view class="charts-box">
      <qiun-data-charts type="column" :opts="opts" :chartData="taskStatisticsData" :echartsH5="true"
                        :echartsApp="true"/>
    </view>

  </view>
</template>

<script>
import IndexAPI from '@/api/index';
import NoticeAPI from '@/api/notice'
import {
  dateFormat,
  getOffsetTime,
  showToast
} from "@/utils/media.js"

export default {
  data() {
    return {
      unreadMessage: [],
      showCalendars: false,
      userInfo: {},
      authority: 'employee',
      listswiper: [], // 首页轮播图
      list: [], // 待办事项
      deptCountList: [], //部门用户数据
      taskStatisticsData: {}, // 任务统计
      scoreStatisticsData: {}, // 评分统计
      dayIncomeExpenditureStatisticsData: {}, // 日收支统计
      monthIncomeExpenditureStatisticsData: {}, // 月收支统计
      attendanceStatisticsData: {}, // 点到统计
      todayIncomeExpenditureData: {}, //今日收支饼图
      rate: 5,
      opts: {
        color: ["#4B98FE", "#00D05E", "#FFAC00", "#FB6A67", "#957BFE", "#00B9FE", "#FE871B", "#00C8B0"],
        padding: [15, 15, 0, 15],
        dataLabel: false, // 是否显示数据标签
        xAxis: {
          disableGrid: true,
        },
        yAxis: {
          gridColor: "rgba(230,230,230,0.6)",
          disabled: false,
          disableGrid: false,
          gridType: 'dash',
          dashLength: '4',
          data: [{
            axisLineColor: "#FFFFFF",
          }],
          min: 0,
          max: 100, // 初始值，后续会动态更新
        },
        legend: {
          show: true, // 是否显示图例
          position: "top", // 图例位置 top bottom left right
          float: "left", // 图例位置 left right top bottom
        },
        extra: {
          column: {
            type: "group", // 柱状图分组
            width: 16,
            activeBgColor: "#000000",
            activeBgOpacity: 0.04,
          },
        },
      },
      activeOpts: {
        color: ["#4B98FE", "#00D05E", "#FFAC00", "#FB6A67", "#957BFE", "#00B9FE", "#FE871B", "#00C8B0"],
        padding: [15, 15, 0, 15],
        dataLabel: false, // 是否显示数据标签
        xAxis: {
          disableGrid: true,
        },
        yAxis: {
          gridColor: "rgba(230,230,230,0.6)",
          disabled: false,
          disableGrid: false,
          gridType: 'dash',
          dashLength: '4',
          data: [{
            axisLineColor: "#FFFFFF",
          }],
          min: 0,
          max: 100, // 初始值，后续会动态更新
        },
        legend: {
          show: true, // 是否显示图例
          position: "top", // 图例位置 top bottom left right
          float: "left", // 图例位置 left right top bottom
        },
        extra: {
          column: {
            type: "stack", // 柱状图分组
            width: 16,
            activeBgColor: "#000000",
            activeBgOpacity: 0.04,
          },
        },
      },

      rangeData: '',
      queryParams: {
        startTime: '',
        endTime: ''
      }
    }
  },

  onShow() {
    this.userInfo = uni.getStorageSync('authInfo') || {}
    this.authority = this.userInfo.authority || 'employee'
    this.getServerData();

    // 默认日期范围
    const afterTime = new Date();
    const beforeTime = getOffsetTime(afterTime, -6);
    this.queryParams.startTime = dateFormat(beforeTime, 'yyyy-MM-dd')
    this.queryParams.endTime = dateFormat(afterTime, 'yyyy-MM-dd')
    this.rangeData = this.queryParams.startTime + ' ~ ' + this.queryParams.endTime
    this.getCalendarsData()
  },
  methods: {
    openCalendars() {
      this.$refs.calendars.open();
    },
    confirmCalendars(e) {
      let me = this;
      console.log(e)
      me.rangeData = e.range.before + ' ~ ' + e.range.after
      me.queryParams.startTime = e.range.before
      me.queryParams.endTime = e.range.after
      me.getCalendarsData()
    },
    onClick(val) {
      console.log(val)
      let item = this.list[val]
      if (item.isAllowJump) {
        console.log(item)
        if (item.linkTyp === 'switchTab') {
          uni.switchTab({
            url: item.url
          })
        } else {
          uni.navigateTo({
            url: item.url
          })
        }

      } else {
        showToast({
          title: "您没有权限查询哦~"
        })
      }
    },
    onClickDeptCount(val) {
      console.log(val)
      let item = this.deptCountList[val]
      if (item.isAllowJump) {
        console.log(item)
        uni.navigateTo({
          url: item.url
        })
      } else {
        showToast({
          title: "您没有权限查询哦~"
        })
      }
    },

    getServerData() {
      // 未读消息
      NoticeAPI.unreadMessageList().then(res => {
        // 获取 res.data 数组中 title 从新组成数据
        if (res.data && Array.isArray(res.data)) {
          this.unreadMessage = res.data.map(item => {
            return item.title
          })
        }
      }).catch(err => {
        console.error('获取未读消息失败:', err)
        this.unreadMessage = []
      })

      // 首页轮播图
      IndexAPI.banner().then(res => {
        this.listswiper = res.data || []
      }).catch(err => {
        console.error('获取轮播图失败:', err)
        this.listswiper = []
      });

      // 待办事项
      IndexAPI.todoList().then(res => {
        this.list = res.data || []
      }).catch(err => {
        console.error('获取待办事项失败:', err)
        this.list = []
      });

      // 任务统计
      IndexAPI.taskStatistics().then(res => {
        this.taskStatisticsData = res.data || {}
      }).catch(err => {
        console.error('获取任务统计失败:', err)
        this.taskStatisticsData = {}
      })

      // 评分统计
      IndexAPI.scoreStatistics().then(res => {
        this.scoreStatisticsData = res.data || {}
      }).catch(err => {
        console.error('获取评分统计失败:', err)
        this.scoreStatisticsData = {}
      })

      // 当月评分
      IndexAPI.monthlyRate().then(res => {
        this.rate = res.data || 5
      }).catch(err => {
        console.error('获取当月评分失败:', err)
        this.rate = 5
      })

      if (this.authority && !this.authority.includes('employee')) {
        // 收支统计（月）
        IndexAPI.monthIncomeExpenditureStatistics().then(res => {
          this.monthIncomeExpenditureStatisticsData = res.data || {}
        }).catch(err => {
          console.error('获取月收支统计失败:', err)
          this.monthIncomeExpenditureStatisticsData = {}
        })
      }
    },
    getCalendarsData() {
      if (this.authority && !this.authority.includes('employee')) {
        // 部门用户数据统计
        IndexAPI.deptUserStatistics().then(res => {
          this.deptCountList = res.data || []
        }).catch(err => {
          console.error('获取部门用户统计失败:', err)
          this.deptCountList = []
        })

        // 点到统计图表
        IndexAPI.attendanceStatistics(this.queryParams).then(res => {
          this.attendanceStatisticsData = res.data || {}
        }).catch(err => {
          console.error('获取考勤统计失败:', err)
          this.attendanceStatisticsData = {}
        })

        // 收支统计（日）
        IndexAPI.dayIncomeExpenditureStatistics(this.queryParams).then(res => {
          this.dayIncomeExpenditureStatisticsData = res.data || {}
        }).catch(err => {
          console.error('获取日收支统计失败:', err)
          this.dayIncomeExpenditureStatisticsData = {}
        })
      }
    },
    onShareAppMessage(res) {
      var path = '/pages/index/index'
      return {
        title: "绩效考核",
        path: path
      }
    },
    onShareTimeline: function () {
      return {
        title: "绩效考核",
        query: 'where=share'
      }
    },
  },
}
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
}

.card {
  // 设置背景色 蓝色
  background-color: #3c9cff;
  // 设置边框
  border: 2px solid #ffffff;
  padding: 10px;
  border-radius: 5px;
  // 设置阴影
  box-shadow: 0 0 3px #3c9cff;
  width: 100%;
  /* 确保卡片宽度适应父元素 */
  box-sizing: border-box;
  /* 包含内边距和边框 */
  margin: 10px;
}

.card-data {

  // 设置边框
  border: 1px solid #3c9cff;
  // 设置宽度
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  // 设置阴影
  box-shadow: 0 0 3px #3c9cff;

}

.rate {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.charts-box {
  width: 100%;
  height: 300px;
}

.uv-calendar {
  z-index: 9999999;
}
</style>